const app = getApp();
const api = require('../../utils/api');

Page({
    data: {
        fromShop: '', //来源店铺

        saleChannel: 0, //0小程序用户 1商家用户 2直播用户
        categoryId: '',
        categoryName: '',
        keywords: '',
        isFocus: false, //搜索框聚焦
        showSearchResult: false,

        sortMethod: '', //排序方式
        sortTypeList: [
            {id: 'price', name: '价格', sortName: '', sortTpye: ''},
            {id: 'member_price', name: '会员价', sortName: '', sortTpye: ''},
            {id: 'coupon_amount', name: '券价格', sortName: '', sortTpye: ''},
        ],

        productList: [], //商品列表
        pageNum: 1,
        pageSize: 10,
        total: 0,
        noContent: false,
        isFinished: false, //加载结束

        inviteCode: '', //邀请人的邀请码
    },
    onLoad(options) {
        // console.log(options)
        this.setData({
            saleChannel: options.saleChannel ? options.saleChannel : 0,
            categoryId: options.categoryId ? options.categoryId : '',
            categoryName: options.categoryName ? options.categoryName : '',
            fromShop: options.from ? parseInt(options.from) : '',
            inviteCode: options.inviteCode ? options.inviteCode : '',
        });

        //设置显示栏目标题
        wx.setNavigationBarTitle({
            title: this.data.categoryName
        });

        this.searchProduct();
    },
    onShow() {
        // this.setData({
        //     isFocus: true
        // });
    },

    searchProduct() { //搜索当前店铺商品
        let params = {
            saleChannel: this.data.saleChannel, //0小程序用户 1商家用户 2直播用户
            platformCategoryId: this.data.categoryId,
            sortMethod: this.data.sortMethod,
            keyword: this.data.keywords,
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
        }
        api.post(`/product/list`, params)
            .then(res => {
                let list = res.content;
                list.forEach(item => {
                    item.price = item.price.toFixed(2);
                });
                let newList = [...this.data.productList, ...list];
                this.setData({
                    productList: newList,
                    total: res.total,
                    showSearchResult: true
                });

                //是否无内容标识
                if(this.data.productList.length == 0) {
                    this.setData({
                        noContent: true
                    })
                } else {
                    this.setData({
                        noContent: false
                    });
                }
                //是否加载完毕标识
                if(this.data.productList.length >= this.data.total) {
                    this.setData({
                        isFinished: true
                    })
                } else {
                    this.setData({
                        isFinished: false
                    })
                }
                wx.stopPullDownRefresh();
            })
    },

    //搜索商品
    bindInput(e) {
        let val = e.detail.value;
        this.setData({
            keywords: val
        });
    },
    clearKeywords() { //清除搜索关键字
        this.setData({
            keywords: ''
        });
    },
    submitSearch() { //提交搜索
        if(!this.data.keywords) {
            wx.showToast({
                title: '请输入搜索商品名称',
                icon: 'none'
            });
            return;
        }
        //重置排序选项
        let list = this.data.sortTypeList;
        list.forEach(i => {
            i.sortName = '';
            i.sortTpye = '';
        });
        this.setData({
            sortTypeList: list,
            sortMethod: '',
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });

        this.searchProduct();
    },

    sortList(e) { //列表排序
        let item = e.currentTarget.dataset.item;
        let newName = ''; //控制箭头方向
        let newType = ''; //提交用参数
        if(item.sortName == 'desc') { //原来是降序
            newName = 'asc';
            newType = 'asc';
        } else if(item.sortName == 'asc') { //原来是升序
            newName = '';
            newType = '';
        } else { //原来是默认状态
            newName = 'desc';
            newType = 'desc';
        }
        //整理选项
        let list = this.data.sortTypeList;
        list.forEach(i => {
            if(i.id == item.id) {
                i.sortName = newName;
                i.sortTpye = newType;
            }
        });
        let resultList = [];
        let resultText = '';
        list.forEach(i => {
            if(i.sortName) {
                resultList.push(i);
            }
        });
        resultList.forEach((i, index) => {
            resultText = resultText + i.id + ':' + i.sortTpye + (index == resultList.length-1 ? '' : ',');
        });
        
        this.setData({
            sortTypeList: list,
            sortMethod: resultText,
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.searchProduct();
    },

    viewProductDetail(e) { //查看商品详情
        let id = e.currentTarget.dataset.id;
        let url = `/pages/productDetail/productDetail?id=${id}&shopId=0&from=${this.data.fromShop}`;
        wx.navigateTo({
            url: url,
        });
    },

    onPullDownRefresh() {
        //下拉刷新
        this.setData({
            productList: [],
            pageNum: 1,
            total: 0,
            isFinished: false,
        });
        this.searchProduct();
    },
    onReachBottom() {
        //加载更多
        if(!this.data.isFinished) {
            this.setData({
                pageNum: this.data.pageNum+1,
            });
            
            setTimeout(() => {
                this.searchProduct();
            }, 800);
        }
    },
    onShareAppMessage() {
        return {
            title: this.data.categoryName,
            desc: this.data.categoryName,
            path: `pages/indexCategoryProduct/indexCategoryProduct?categoryId=${this.data.categoryId}&categoryName=${this.data.categoryName}&inviteCode=${app.globalData.userInfo.invitationCode}`, // 路径，传递参数到指定页面
            // imageUrl: '',
        }
    }
})